﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;
using System.Data;

public partial class CRM_Store_ERP_PerReturnEdit : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string objid = ViewState_ObjID = string.IsNullOrEmpty(Request.QueryString["ObjId"]) ? "Add" : Request.QueryString["ObjId"];
            ShowEditInfo(objid);
            StoreBind();
        }
    }

    private void StoreBind()
    {
        DataTable dt = CRMMis.BLL.ERP_Customer.GetList("1=1").Tables[0];
        Store_Customer.DataSource = dt;
        Store_Customer.DataBind();
    }

    private void ShowEditInfo(string objid)
    {
        if (objid == "Add")
        {
            exttxtf_InUser_Name.Text = BS_LoginUserName;
            exthidn_InUser.Text = BS_LoginUserID;
            exttxtf_InDate.Text = DateTime.Now.ToDateTimeString();
            exttxtf_OwnerName.Text = BS_LoginUserName;
        }
        else
        {
            var planDataTable = CRMMis.BLL.ERP_PerReturn.GetList("PerReturnId=" + objid).Tables[0];
            if (planDataTable.Rows.Count > 0)
            {
                DataRow row = planDataTable.Rows[0];
                int planState = Convert.ToInt32(row["State"]);
                //根据状态控制
                if (planState != 1)
                    extBtn_CheckInfo.Hidden = true;
                if (planState > 0)
                {
                    extBtn_SubmitInfo.Hidden = true;
                    extBtn_Save.Hidden = true;
                    extBtn_AddItem.Hidden = extBtn_DeleteItem.Hidden = true;
                    SetContainerReadOnly(formPanel, true);
                    gridPanel_listdata.ColumnModel.Columns[1].Editable =                //商品名称
                        gridPanel_listdata.ColumnModel.Columns[6].Editable = false;     //数量
                }
                if (planState > 1)
                {
                    extBtn_CheckInfo.Hidden = true;
                }
            }
            SetContainer(formPanel, planDataTable);


            var planDetail = CRMMis.BLL.ERP_PerReturnDetail.GetList(" PerReturnId=" + objid).Tables[0];
            Store1.DataSource = planDetail;
            Store1.DataBind();
        }
    }

    [DirectMethod]
    public void BindCargoComb(string searchText)
    {
        string sqWhere = " 1=1 ";
        if (!string.IsNullOrEmpty(searchText))
        {
            sqWhere = " CargoName like '%" + FilterSpecChar(searchText) + "%' or Spell like '%" + FilterSpecChar(searchText) + "%' ";
        }
        var datatable = CRMMis.BLL.ERP_PersonStockDetail.GetList(sqWhere, " CargoName asc");
        store_Cargo.DataSource = datatable;
        store_Cargo.DataBind();
    }

    /// <summary>
    /// 保存，
    /// </summary>
    /// <param name="jsonData"></param>
    /// <param name="type">0,保存;1,提交;2,审核</param>
    [DirectMethod]
    public void SaveData(string jsonData, int type)
    {
        List<CRMMis.Model.ERP_PerReturnDetail> details = JSON.Deserialize<List<CRMMis.Model.ERP_PerReturnDetail>>(jsonData);
        CRMMis.Model.ERP_PerReturn returnModel;
        if (ViewState_ObjID == "Add")
        {
            returnModel = new CRMMis.Model.ERP_PerReturn();
            returnModel.PerReturnId = CRMMis.BLL.ERP_PerReturn.GetNewID();
            returnModel.PerReturnNo = GetBusinessNo("TH", "ERP_PerReturnTH", Convert.ToInt32(extcomb_CustomerId.SelectedItem.Value).ToString("0000"));
            returnModel.InUser = BS_LoginUserID;
            returnModel.InDate = exttxtf_InDate.Text.Trim();
            returnModel.Owner= BS_LoginUserID;
            returnModel.State = 0;
            if (type == 1)
                returnModel.State = 1;    //提交
        }
        else
        {
            returnModel = CRMMis.BLL.ERP_PerReturn.GetModel(Convert.ToInt32(ViewState_ObjID));
            if (type == 1)
            {
                if (returnModel.State == 0)
                    returnModel.State = 1;    //提交
                else
                {
                    X.Msg.Alert("系统提示", "提交失败！当前记录已经提交").Show();
                    return;
                }
            }
            else if (type == 2)
            {
                if (returnModel.State == 1)
                {
                    returnModel.State = 2;    //审核
                    returnModel.CheckDate = System.DateTime.Now.ToString();
                    returnModel.CheckUser = BS_LoginUserID;
                }
                else
                {
                    X.Msg.Alert("系统提示", "审核失败！当前记录已经审核").Show();
                    return;
                }
            }

        }
        if (type < 2)
        {
            returnModel.CustomerId = Convert.ToInt32(extcomb_CustomerId.SelectedItem.Value);
            returnModel.Remark = exttxtf_Remark.Text.Trim();
            returnModel.Owner = exthidn_InUser.Text.Trim();
        }
        CommonLib.BLL.MyTransaction myTrans = new CommonLib.BLL.MyTransaction();
        myTrans.BeginTransaction();
        try
        {
            if (ViewState_ObjID == "Add")
            {
                CRMMis.BLL.ERP_PerReturn.Add(myTrans, returnModel);
            }
            else
            {
                CRMMis.BLL.ERP_PerReturn.Update(myTrans, returnModel);
                //删除子表
                if (type < 2)
                    CRMMis.BLL.ERP_PerReturnDetail.DeleteFK(myTrans, "PerReturnId = " + returnModel.PerReturnId);
            }
            if (type < 2)
            {
                int j = 1;
                foreach (CRMMis.Model.ERP_PerReturnDetail detailModel in details)
                {
                    detailModel.DetailId = CRMMis.BLL.ERP_PerReturnDetail.GetNewID();
                    detailModel.PerReturnId = returnModel.PerReturnId;
                    detailModel.OrderId = j;
                    CRMMis.BLL.ERP_PerReturnDetail.Add(myTrans, detailModel);
                    j++;
                }
            }
            if (type == 2)
            {
                foreach (CRMMis.Model.ERP_PerReturnDetail detailModel in details)
                {
                    CRMMis.Model.ERP_BusinessLog BusModel = new CRMMis.Model.ERP_BusinessLog();
                    BusModel.LogId = CRMMis.BLL.ERP_BusinessLog.GetNewID();
                    BusModel.ActionId = 8;
                    BusModel.ActionName = "售还";
                    BusModel.ActionUser = returnModel.InUser;
                    BusModel.StoreRoom_Id = returnModel.Owner;
                    BusModel.ActionDate = returnModel.CheckDate;
                    CRMMis.Model.ERP_PersonStockDetail sModel = CRMMis.BLL.ERP_PersonStockDetail.GetModel(myTrans, detailModel.ItemId);
                    sModel.Count = sModel.Count + detailModel.Count;
                    CRMMis.BLL.ERP_PersonStockDetail.Update(myTrans, sModel);
                    CRMMis.Model.ERP_PersonStock iModel = CRMMis.BLL.ERP_PersonStock.GetModel(myTrans, sModel.StoreId);
                    BusModel.DetailId = iModel.DetailId;
                    DataTable dt = CRMMis.BLL.ERP_Cargo_Detail.GetList("DetailId=" + iModel.DetailId).Tables[0];
                    BusModel.CargoName = dt.Rows[0]["CargoName"].ToString();
                    BusModel.Spec = dt.Rows[0]["Spec"].ToString();
                    BusModel.Area = dt.Rows[0]["Area"].ToString();
                    BusModel.Version = dt.Rows[0]["Version"].ToString();
                    BusModel.ProduceName = dt.Rows[0]["ProduceName"].ToString();
                    BusModel.BatchNo = sModel.BatchNo;
                    BusModel.SupplyPrice = decimal.Parse(dt.Rows[0]["SupplyPrice"].ToString());
                    BusModel.CustomId = returnModel.CustomerId;
                    BusModel.CurCount = iModel.Count;
                    BusModel.Count = detailModel.Count;
                    BusModel.State = 0;
                    BusModel.BusniessNo = returnModel.PerReturnNo;
                    iModel.Count = iModel.Count + detailModel.Count;
                    CRMMis.BLL.ERP_PersonStock.Update(myTrans, iModel);
                    if (sModel.Count < 0 || iModel.Count < 0)
                        throw new Exception("库存数量不足,请检查！");
                    CRMMis.BLL.ERP_BusinessLog.Add(myTrans, BusModel);
                }
            }
            myTrans.CommitTran();
            ViewState_ObjID = returnModel.PerReturnId.ToString();
            exttxtf_PerReturnNo.Text = returnModel.PerReturnNo;

            string handler = "";
            if (type > 0)
                handler = "closeCurrTab();";
            X.Msg.Alert("系统提示", "保存成功！", handler).Show();
        }
        catch (Exception ex)
        {
            myTrans.RollBackTran();
            X.Msg.Alert("系统提示", "保存失败！</br>" + ex.Message).Show();
        }
    }
}